﻿using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using Prism.Services.Dialogs;
using System.Collections.ObjectModel;
using WPF.Core;
using WPF.Core.Dtos;
using WPF.Core.Services;
using static WPF.Core.Dtos.NoteBookModel;

namespace WPF.NoteBook.ViewModels
{
    public partial class NoteBookViewModel : NavigateViewModel
    {
        private readonly INoteBookService appService;
        private readonly IDialogService dialog;

        [ObservableProperty]
        private NoteBookPagingInfo paging;

        [ObservableProperty]
        private ObservableCollection<NoteBookModel> gridModelList;


        public NoteBookViewModel(INoteBookService appService, IDialogService dialog)
        {
            GridModelList = new ObservableCollection<NoteBookModel>();
            this.appService = appService;
            Paging = new NoteBookPagingInfo()
            {
                PageNumber = 1,
                PageSize = 1,
            };
            this.dialog = dialog;
        }

        [RelayCommand]
        private void Add()
        {
            dialog.ShowDialog("CreateNoteBookView", async callBack =>
            {
                if (callBack.Result == ButtonResult.OK)
                    await GetAllAsync();
            });
        }

        [RelayCommand]
        private void Search()
        {
            GetAllAsync();
        }

        [RelayCommand]
        private async Task Delete(NoteBookModel model)
        {
            //删除数据库数据
            await appService.Delete(model.Id);
            var todo = GridModelList.FirstOrDefault(x => x.Id == model.Id);
            if (todo != null)
            {
                //界面数据删除
                GridModelList.Remove(todo);
            }
        }

        [RelayCommand]
        private void Edit(NoteBookModel model)
        {
            DialogParameters param = new DialogParameters();
            param.Add("Value", model);
            dialog.ShowDialog("CreateNoteBookView", param, async callBack =>
            {
                if (callBack.Result == ButtonResult.OK)
                {
                    await GetAllAsync();
                }
            });
        }

        [RelayCommand]
        public async Task Pageing()
        {
            await GetAllAsync();
        }

        /// <summary>
        /// 获取所有
        /// </summary>
        /// <returns></returns>
        private async Task GetAllAsync()
        {
            var models = await appService.GetAll(paging);
            GridModelList.Clear();
            if (models != null)
            {
                foreach (var model in models)
                {
                    GridModelList.Add(model);
                }
            }
        }
    }
}
